﻿using lcwb.Shared.Api;
using System.Net.Http.Json;

namespace lcwb.Shared.Service.Interface
{
    // ApiService.cs
    public class ApiService
    {
        private readonly HttpClient _httpClient;

        public ApiService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<ApiResponse<T>> GetAsync<T>(string url)
        {
            try
            {
                var response = await _httpClient.GetAsync(url);
                return await HandleResponse<T>(response);
            }
            catch (Exception ex)
            {
                return ApiResponse<T>.Error("网络请求失败");
            }
        }

        public async Task<ApiResponse<T>> PostAsync<T>(string url, object content)
        {
            try
            {
                var response = await _httpClient.PostAsJsonAsync(url, content);
                return await HandleResponse<T>(response);
            }
            catch (Exception ex)
            {
                return ApiResponse<T>.Error("网络请求失败");
            }
        }

        private async Task<ApiResponse<T>> HandleResponse<T>(HttpResponseMessage response)
        {
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadFromJsonAsync<ApiResponse<T>>();
            }
            else
            {
                var error = await response.Content.ReadAsStringAsync();
                return ApiResponse<T>.Error($"请求失败: {error}");
            }
        }
    }
}
